﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using RainEngine.SceneNodes;

namespace RainEngine.Controllers
{
    /// <summary>
    /// 控制模型的移动。
    /// 用键盘上下左右或WSAD控制模型的前进后退左转右转。
    /// </summary>
    public class ModelController : Controller
    {
        #region 构造函数和成员变量
        /// <summary>
        /// 要控制的ModelSceneNode。
        /// </summary>
        protected ModelSceneNode model;        

        /// <summary>
        /// 模型旋转的总角度
        /// </summary>
        protected float angle = 0;

        /// <summary>
        /// 创建一个新ModelController对象。
        /// </summary>
        /// <param name="engine">引擎</param>
        public ModelController(RainGE engine): base(engine)
        {
            
        }
        #endregion
        
        /// <summary>
        /// 主控制逻辑
        /// </summary>
        /// <param name="gameTime"></param>
        public override void ControllerAction(GameTime gameTime)
        {
            if (model == null)
            {
                model = (ModelSceneNode )controlledNode;                
            }
            float timeDifference = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000.0f;
            ProcessInput(timeDifference);
        }

        private void ProcessInput(float elapsedTime)
        {
            float movement = 0;
            float rotation = 0;

            //模型相机每帧旋转和移动距离
            float rotationPerFrame = elapsedTime * model.RotationSpeed;
            float movementPerFrame = elapsedTime * model.MovementSpeed;

            if (Input.KeyboardUpPressed ||Input.Keyboard .IsKeyDown (Keys.W))
                movement += movementPerFrame;
            if (Input.KeyboardDownPressed || Input.Keyboard .IsKeyDown(Keys.S))
                movement -= movementPerFrame;
            if (Input.KeyboardRightPressed || Input.Keyboard.IsKeyDown(Keys.D))
                rotation += rotationPerFrame;
            if (Input.KeyboardLeftPressed || Input.Keyboard.IsKeyDown(Keys.A))
                rotation -= rotationPerFrame;            

            angle += rotation;            
            model.AngleRotation = new Vector3(0, angle, 0);
            model.Pose.Rotation = Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(-model.AngleRotation.Y), 0, 0);
            model.Pose.SetRotation(ref model.Pose.Rotation);
            
            if (movement != 0)
            {
                Quaternion fpsRotation = Quaternion.CreateFromYawPitchRoll(MathHelper.ToRadians(-model.AngleRotation.Y), 0, 0);
                Vector3 addVector = Vector3.Transform(Vector3.Forward, fpsRotation)* movement;
                model.Pose.Position -= addVector ; 
                model.Pose.SetPosition(ref model.Pose.Position);
            }
        }        
    }
}
